<script setup lang="ts">
import { ref, onMounted, onUpdated } from 'vue'
import { isLogin, getUsers } from '../../util/SessionUtil'
import { db } from '../../db/db'
import $ from 'jquery'
import 'bootstrap/dist/js/bootstrap'
import { DateTime } from 'luxon'
import { v4 as uuidv4 } from 'uuid'

const salvationData: any = ref([])
const organizeData: any = ref([])

const salvationPage = ref({
  totalCount: 0,
  pageNumber: 1,
  pageSize: 6,
  totalPages: 0
})

const lookMorePet = async () => {
  salvationPage.value.pageNumber = salvationPage.value.pageNumber + 1
  loadSalvationData()
}

const loadSalvationData = async () => {
  // 救助信息
  let tempSd = []
  const salvation = await db.salvation.orderBy('createDate').reverse().offset((salvationPage.value.pageNumber - 1) * salvationPage.value.pageSize)
    .limit(salvationPage.value.pageSize).toArray()
  for (let i in salvation) {
    let pimge = ''
    const petImage = await db.petImage.where('salvationId').equals(salvation[i].salvationId).limit(1).toArray()
    pimge = petImage[0].petImageUrl

    let isCollection = false
    if (judgeLogin.value) {
      const collections = await db.collection.where('salvationId').equals(salvation[i].salvationId)
        .and(collection => collection.username === curUsers.value.username).toArray()
      isCollection = collections && collections.length > 0
    }


    tempSd.push({
      salvationId: salvation[i].salvationId,
      petSituation: salvation[i].petSituation,
      createDate: salvation[i].createDate,
      petImageUrl: pimge,
      isCollection: isCollection
    })
  }



  for (let i in tempSd) {
    salvationData.value.push(tempSd[i])
  }

}

const judgeLogin = ref(false)
const curUsers: any = ref({})

onMounted(async () => {

  // 是否登录
  const okLoing = isLogin()
  judgeLogin.value = okLoing
  curUsers.value = getUsers()

  // 救助页数
  const totalCount = await db.salvation.count()
  const totalPages = Math.ceil(totalCount / salvationPage.value.pageSize)

  salvationPage.value.totalCount = totalCount
  salvationPage.value.totalPages = totalPages

  loadSalvationData()

  // 组织信息
  let tempOr = []
  const organize = await db.organize.orderBy('organizeId').reverse().limit(4).toArray()
  for (let i in organize) {

    const organizeImages = await db.organizeImages.where('organizeId').equals(Number(organize[i].organizeId)).limit(1).toArray()
    const organizeDetail = await db.organizeDetail.where('organizeId').equals(Number(organize[i].organizeId)).limit(1).toArray()
    const users = await db.users.where('username').equals(organize[i].username).toArray()

    if (organizeImages && organizeImages.length > 0 && organizeDetail && organizeDetail.length > 0) {
      tempOr.push({
        organizeId: organize[i].organizeId,
        realName: users[0].realName,
        imageUrl: organizeImages[0].imageUrl,
        content: organizeDetail[0].content
      })
    }

  }

  organizeData.value = tempOr

  if (okLoing) {
    commentsSend.value.canSend = true
    commentsSend.value.tip = '爱心传递，注意文明用语哦'
  } else {
    commentsSend.value.canSend = false
    commentsSend.value.tip = '登录后可评论'
  }
})

const petDetail = ref({
  content: '',
  images: new Array<any>(),
  petSalvationPlanData: new Array<any>()
})

const lookPetDetail = async (salvationId: string) => {
  const salvation = await db.salvation.where('salvationId').equals(salvationId).toArray()
  petDetail.value.content = salvation[0].petSituation
  const petImage: any = await db.petImage.where('salvationId').equals(salvationId).toArray()
  petDetail.value.images = petImage

  let tempUpdateData: any = []
  const tempData = await db.petSalvationPlan.where('salvationId').equals(salvationId).reverse().sortBy('petSalvationPlanDate')
  for (let i = 0; i < tempData.length; i++) {
    let organizeName = ''
    if (tempData[i] && tempData[i].organizeId) {
      const organize: any = await db.organize.where('organizeId').equals(Number(tempData[i].organizeId)).toArray()
      organizeName = organize[0].organizeName
    }

    tempUpdateData.push({
      petSalvationPlanId: tempData[i].petSalvationPlanId,
      node: tempData[i].node,
      situation: tempData[i].situation,
      organizeId: tempData[i].organizeId,
      salvationId: tempData[i].salvationId,
      petSalvationPlanDate: tempData[i].petSalvationPlanDate,
      organizeName: organizeName
    })

  }

  petDetail.value.petSalvationPlanData = tempUpdateData

  $('#petDetailModal').modal('show')
}

const organizeDetailData = ref({
  realName: '',
  joinDate: '',
  content: '',
  imageUrl: '',
  address: ''
})


const lookOrganizeDetail = async (organizeId: number) => {
  const organize = await db.organize.where('organizeId').equals(organizeId).toArray()
  const organizeImages = await db.organizeImages.where('organizeId').equals(Number(organizeId)).limit(1).toArray()
  const organizeDetail = await db.organizeDetail.where('organizeId').equals(Number(organizeId)).limit(1).toArray()
  const users = await db.users.where('username').equals(organize[0].username).toArray()

  organizeDetailData.value.realName = users[0].realName ? users[0].realName : ''
  organizeDetailData.value.joinDate = users[0].joinDate ? users[0].joinDate : ''
  organizeDetailData.value.content = organizeDetail[0].content
  organizeDetailData.value.imageUrl = organizeImages[0].imageUrl
  organizeDetailData.value.address = organize[0].address

  $('#organizeDetailModal').modal('show')
}

const commentsSend = ref({
  canSend: false,
  tip: '',
  content: '',
  errMsg: '',
  salvationId: ''
})

const commentsData: any = ref([])

const loadComments = async (salvationId: string) => {
  let tempData = []
  const comments = await db.comment.where('salvationId').equals(salvationId).sortBy('commentDate')
  for (let i in comments) {
    const usersData = await db.users.where('username').equals(comments[i].username).toArray()
    tempData.push({
      commentId: comments[i].commentId,
      commentContent: comments[i].commentContent,
      commentDate: DateTime.fromFormat(comments[i].commentDate, "yyyy-LL-dd HH:mm:ss").toRelative(),
      realName: usersData[0].realName,
      avatar: usersData[0].avatar,
      salvationId: comments[i].salvationId
    })
  }

  commentsData.value = tempData
}

const openComments = async (salvationId: string) => {
  commentsSend.value.salvationId = salvationId
  loadComments(salvationId)
  $('#commentsModal').modal('show')
}

const scrollContainer:any = ref(null)

const addComment = () => {
  const salvationId = commentsSend.value.salvationId
  commentsSend.value.errMsg = ''
  if (commentsSend.value.content === '') {
    commentsSend.value.errMsg = '请填写评论内容'
    return
  }
  db.comment.add({
    commentId: uuidv4(),
    commentContent: commentsSend.value.content,
    salvationId: salvationId,
    username: curUsers.value.username,
    commentDate: DateTime.now().toFormat('yyyy-LL-dd HH:mm:ss')
  })

  loadComments(salvationId)

  commentsSend.value.content = ''
}

onUpdated(() => {
  if (scrollContainer.value) {
    scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
  }

})

const tipModal = ref({
  class: '',
  title: '',
  content: ''
})

const collectionData = ref({
  salvationId: '',
  isCollection: false,
  remarks: ''
})
const openCollection = (salvationId: string, isCollection: boolean) => {
  if (judgeLogin.value) {
    collectionData.value.salvationId = salvationId
    collectionData.value.isCollection = isCollection
    if (!collectionData.value.isCollection) {
      $('#collectionModal').modal('show')
    } else {
      addCollection()
    }
  } else {
    tipModal.value.class = 'text-info'
    tipModal.value.title = '未登录'
    tipModal.value.content = '您好，请登录后进行操作！'
    $('#tipModal').modal('show')
  }


}

const addCollection = async () => {
  if (collectionData.value.salvationId === '') {
    return false
  }
  if (!collectionData.value.isCollection) {
    db.collection.add({
      collectionId: uuidv4(),
      salvationId: collectionData.value.salvationId,
      collectionDate: DateTime.now().toFormat('yyyy-LL-dd HH:mm:ss'),
      remarks: collectionData.value.remarks,
      username: curUsers.value.username
    })
    for (let i in salvationData.value) {
      if (collectionData.value.salvationId === salvationData.value[i].salvationId) {
        salvationData.value[i].isCollection = true
      }
    }

    $('#collectionModal').modal('hide')
    tipModal.value.class = 'text-success'
    tipModal.value.title = '收藏成功'
    tipModal.value.content = '您好，收藏已添加成功！'
    $('#tipModal').modal('show')
  } else {
    db.collection.where('salvationId').equals(collectionData.value.salvationId).delete()
    for (let i in salvationData.value) {
      if (collectionData.value.salvationId === salvationData.value[i].salvationId) {
        salvationData.value[i].isCollection = false
      }
    }

    tipModal.value.class = 'text-success'
    tipModal.value.title = '取消收藏成功'
    tipModal.value.content = '您好，已取消该收藏！'
    $('#tipModal').modal('show')
  }

  collectionData.value.salvationId = ''
  collectionData.value.isCollection = false


}

const svg = ref(
  '<svg style="-webkit-transform: rotate(-180deg);-moz-transform: rotate(-180deg);-o-transform: rotate(-180deg);transform: rotate(-180deg);margin-top: -26px;enable-background: new 0 0 1440 126;" version="1.1" id="Layer_1" ' +
  'xmlns="http://www.w3.org/2000/svg" ' +
  'xmlns:xlink="http://www.w3.org/1999/xlink" ' +
  'x="0px" ' +
  'y="0px" ' +
  'viewbox="0 0 1440 126" ' +
  'xml:space="preserve" ' +
  '>' +
  '<path ' +
  'class="bg-primary" ' +
  'd="M685.6,38.8C418.7-11.1,170.2,9.9,0,30v96h1440V30C1252.7,52.2,1010,99.4,685.6,38.8z"' +
  '/>' +
  '</svg>'
)
</script>

<template>
  <header>
    <div class="jumbotron jumbotron-lg jumbotron-fluid mb-0 pb-3 bg-primary position-relative">
      <div class="container-fluid text-white h-100">
        <div class="d-lg-flex align-items-center justify-content-between text-center pl-lg-5">
          <div class="col pt-4 pb-4">
            <h1 class="display-3">校园 <strong>萌宠</strong> 救助</h1>
            <h5 class="font-weight-light mb-4">
              爱护动物，从点滴做起。保护生态，共建美好明天。
              <strong><font-awesome-icon icon="leaf" class="fa-2x text-info" /></strong>
            </h5>
            <RouterLink to="/web/salvation" class="btn btn-lg btn-info btn-round mr-2">
              发起救助 <font-awesome-icon icon="hand-holding-heart" />
            </RouterLink>
            <RouterLink to="/web/donation/1" class="btn btn-lg btn-danger btn-round">
              捐赠
            </RouterLink>
          </div>
          <div
            class="col align-self-bottom align-items-right text-right h-max-380 h-xl-560 position-relative z-index-1">
            <img src="/img/dashb.png" class="rounded img-fluid" />
          </div>
        </div>
      </div>
    </div>
    <div v-html="svg"></div>
  </header>

  <main class="container">
    <!--------------------------------------
CARDS
--------------------------------------->
    <section class="pt-4 pb-5" data-aos="fade-up">
      <h3 class="h5 mb-4 mt-5 font-weight-bold">救助展示</h3>
      <div class="row">
        <div class="col-md-4" v-for="item in salvationData" :key="item.salvationId">
          <div class="card shadow-sm border-0">
            <img class="card-img-top" :src="item.petImageUrl" alt="Card image cap"
              style="width: 300px; height: 200px;" />
            <div class="card-body">
              <h5 class="card-title">{{ item.createDate }}</h5>
              <p class="card-text text-muted text-truncate">
                {{ item.petSituation }}
              </p>
              <div class="text-right">
                <font-awesome-icon icon="eye" style="font-size: 1.2rem;" class=" mr-3"
                  @click="lookPetDetail(item.salvationId)" />

                <font-awesome-icon icon="comments" style="font-size: 1.2rem;" class="text-info mr-3"
                  @click="openComments(item.salvationId)" />

                <font-awesome-icon icon="archive" style="font-size: 1.2rem;"
                  :class="item.isCollection ? 'text-danger' : 'text-black'"
                  @click="openCollection(item.salvationId, item.isCollection)" />

              </div>
            </div>
          </div>
        </div>
        <div class="col-12 text-center" v-if="salvationPage.pageNumber < salvationPage.totalPages">
          <a href="javascript:;" class="btn btn-outline-secondary mt-4" @click="lookMorePet">查看更多</a>
        </div>
      </div>
    </section>

    <section class="pt-4 pb-5" data-aos="fade-up">
      <h3 class="h5 mb-4 font-weight-bold">入驻组织/商家</h3>
      <div class="row">
        <div class="col-lg-6" v-for="item in organizeData" :key="item.organizeId">
          <div class="card bg-dark overlay overlay-black text-white shadow-sm border-0">
            <img class="card-img" :src="item.imageUrl" alt="Card image" style="width: 450px; height: 300px;">
            <div class="card-img-overlay d-flex align-items-center text-center">
              <div class="card-body">
                <h3 class="card-title">{{ item.realName }}</h3>
                <p class="card-text text-muted">
                  {{ item.content }}
                </p>
                <a href="javascript:;" class="btn btn-purple btn-round"
                  @click="lookOrganizeDetail(item.organizeId)">查看详情</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <section class="pt-5 pb-5 bg-warning rounded mt-5 mb-5" data-aos="zoom-in">
      <div class="container text-center">
        <h1><font-awesome-icon icon="dove" /></h1><br>
        <h1 class="mb-3 mt-3">关于我们</h1>
        <h3 class="font-weight-light mb-5">
          校园萌宠救助系统旨在为校园流浪萌宠提供帮助与<em><strong>关爱</strong></em>。我们用科技力量搭建救助桥梁，通过系统，实现信息共享、救助协同，让每一只萌宠都能感受到温暖与关怀，共同为校园萌宠创造美好未来。
        </h3>
      </div>
    </section>

    <!--------------------------------------
END
--------------------------------------->
  </main>

  <!--宠物详情-->
  <div class="modal fade" id="petDetailModal" tabindex="-1" aria-labelledby="petDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="petDetailModalLabel">救助详情</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="row">
            <div class="col-md-6">
              <p class="mb-1">
                {{ petDetail.content }}
              </p>

              <div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
                <div class="carousel-inner">
                  <div class="carousel-item" v-for="(item, index) in petDetail.images"
                    :class="index == 0 ? 'active' : ''">
                    <img :src="item.petImageUrl" class="d-block w-100" alt="宠物图片">
                  </div>
                </div>
                <button class="carousel-control-prev" type="button" data-target="#carouselExampleControls"
                  data-slide="prev">
                  <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                  <span class="sr-only">Previous</span>
                </button>
                <button class="carousel-control-next" type="button" data-target="#carouselExampleControls"
                  data-slide="next">
                  <span class="carousel-control-next-icon" aria-hidden="true"></span>
                  <span class="sr-only">Next</span>
                </button>
              </div>
            </div>
            <div class="col-md-6">
              <div class="container">
                <ul class="timeline">
                  <li class="timeline-item" v-for="item in petDetail.petSalvationPlanData"
                    :key="item.petSalvationPlanId">
                    <div class="timeline-badge" style="background-color:#4189c9"><font-awesome-icon icon="check" />
                    </div>
                    <div class="timeline-panel">
                      <div class="timeline-heading">
                        <h6>{{ item.petSalvationPlanDate }}</h6>
                      </div>
                      <div class="timeline-body">
                        <p>节点：{{ item.node }}</p>
                        <p>状况：{{ item.situation }}</p>
                        <p>救助组织：{{ item.organizeName }}</p>
                      </div>
                    </div>
                  </li>
                  <!-- 更多时间点... -->
                </ul>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <!--组织详情-->
  <div class="modal fade" id="organizeDetailModal" tabindex="-1" aria-labelledby="organizeDetailModalLabel"
    aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="organizeDetailModalLabel">组织/商家详情</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="card flex-md-row mb-4 box-shadow h-xl-300">
            <div class="card-body d-flex flex-column align-items-start">
              <strong class="d-inline-block mb-2 text-purple">Business</strong>
              <h3 class="mb-0">
                <a class="text-dark" href="#">{{ organizeDetailData.realName }}</a>
              </h3>
              <div class="mb-1 text-muted">
                {{ organizeDetailData.joinDate }}
              </div>
              <p class="card-text mb-auto">
                {{ organizeDetailData.content }}
              </p>
              <span class="text-gray">地址：{{ organizeDetailData.address }}</span>
            </div>
            <img class="card-img-right flex-auto d-none d-md-block" :src="organizeDetailData.imageUrl"
              style="max-width: 450px; max-height: 300px;">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <!--评论-->
  <div class="modal fade" id="commentsModal" tabindex="-1" aria-labelledby="commentsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="commentsModalLabel">评论</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="row">
            <div class="col-12">
              <div class="scrollable-div" style="height: 200px;overflow-y: scroll;" ref="scrollContainer">
                <div class="toast ml-2 mb-3" role="alert" aria-live="assertive" aria-atomic="true"
                  v-for="item in commentsData" :key="item.commentId">
                  <div class="toast-header">
                    <img :src="item.avatar" class="rounded mr-2" alt="头像" style="width: 20px; height: 20px;">
                    <strong class="mr-2">{{ item.realName }}</strong>
                    <small>{{ item.commentDate }}</small>
                  </div>
                  <div class="toast-body">
                    {{ item.commentContent }}
                  </div>
                </div>
              </div>
            </div>
            <div class="col-12">
              <div class="input-group mb-3">
                <input type="text" class="form-control" :placeholder="commentsSend.tip" :aria-label="commentsSend.tip"
                  aria-describedby="button-addon2" :disabled="!commentsSend.canSend" v-model.trim="commentsSend.content"
                  @keyup.enter="addComment">
                <div class="input-group-append">
                  <button class="btn btn-outline-secondary" type="button" :disabled="!commentsSend.canSend"
                    @click="addComment">
                    发表
                    <font-awesome-icon icon="paper-plane" />
                  </button>
                </div>
              </div>
              <div class="text-danger">
                {{ commentsSend.errMsg }}
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <div class="modal fade" id="collectionModal" tabindex="-1" aria-labelledby="collectionModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" :class="tipModal.class" id="collectionModalLabel">收藏</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form>
            <div class="form-group">
              <input type="text" class="form-control" v-model.trim="collectionData.remarks" placeholder="备注(选填)" />
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" @click="addCollection">确定</button>
        </div>
      </div>
    </div>
  </div>

  <div class="modal fade" id="tipModal" tabindex="-1" aria-labelledby="tipModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" :class="tipModal.class" id="tipModalLabel">{{ tipModal.title }}</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          {{ tipModal.content }}
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
.timeline {
  list-style: none;
  padding: 20px 0;
  position: relative;
}

.timeline:before {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  width: 5px;
  background: #eee;
  left: 50%;
  margin-left: -2.5px;
}

.timeline-item {
  margin-bottom: 20px;
  position: relative;
}

.timeline-item:before,
.timeline-item:after {
  content: '';
  display: table;
}

.timeline-item:after {
  clear: both;
}

.timeline-badge {
  color: white;
  width: 50px;
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  text-align: center;
  position: absolute;
  top: 0;
  left: 50%;
  margin-left: -25px;
  background-color: #6c757d;
  border-radius: 50%;
  z-index: 100;
}

.timeline-body {
  margin-left: 0px;
  margin-right: 15px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 15px;
  position: relative;
}
</style>